// 引入axios
import axios from 'axios'
import {baseAPI} from "@/core/config/ApiConfig";
import store from "@/store";
import SafeUtils from "@/core/utils/SafeUtils";
import CryptoJS from "crypto-js";
import Vue from "vue";
import router from "@/core/RouterConfig";
// import CryptoJS from "crypto-js";
export var request=axios.create()
request.defaults.baseURL = baseAPI
request.defaults.crossDomain = true
request.defaults.withCredentials = true //设置cross跨域 并设置访问权限 允许跨域携带cookie信息
request.interceptors.request.use(config=>{
    var timeStamp=new Date().getTime()
    var token = "default"
    if (store.state.user.token!=token){
        token = store.state.user.token
    }
    config.headers['Authorization']=token;
    config.headers['Uuid']=store.state.user.uuid
    config.headers['X-Ca-Timestamp']=timeStamp;
    // nonce 为 6 位随机数字+userAccount md5加密
    var md5 = CryptoJS.MD5(Math.floor( Math.random()*900000+100000).toString()+token);
    var randomNonce = md5.toString().substring(0,Math.random()*10+5);
    // ip 保证唯一性
    // 几个人 同时使用一个IP
    // userAccount =》
    config.headers['X-Ca-Nonce']=randomNonce;
    config.headers['X-Ca-Sign']=SafeUtils.signByRequest(randomNonce,timeStamp);
    // if (baseAPI=="https://bright-dog-ruling.ngrok-free.app/api") {
    // config.headers['ngrok-skip-browser-warning']='ok'
    // }
    return config
})
request.interceptors.response.use(res=>{
    // alert(res.data.code)
    // router.push(`/login?redirect=${location.href.substring(8+location.href.substring(8).indexOf('/'))}`)
    if(res.data.code&&Math.floor(res.data.code)==40&&res.data.code!=40000){
        sessionStorage.removeItem('loginStatus')
        sessionStorage.removeItem('store')
        store.state.user.token = ''
        store.state.user.uuid = ''
        router.push(`/login?redirect=${location.href.substring(8+location.href.substring(8).indexOf('/'))}`)
    }
    else if (res.data.code){
        new Vue().$message.error(res.data.message)
    }
    return res
},err=>{
    if (err&&err.response&&err.response.status&&err.response.data&&err.response.data.code&&err.response.data.code!=40000){
        new Vue().$message.error(err.response.data.message)
        sessionStorage.removeItem('loginStatus')
        sessionStorage.removeItem('store')
        store.state.user.token = ''
        store.state.user.uuid = ''
        router.push(`/login?redirect=${location.href.substring(8+location.href.substring(8).indexOf('/'))}`)
        Object.assign(err,{data:err.response})
        return Promise.resolve(err)
    }
})